package com.lwl.leetcode;

import org.junit.Test;

/**
 * @author lwl
 * @Description 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * @date 2023/7/28 14:27
 */
public class Code19RemoveNthFromEnd {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    @Test
    public void test() {
        ListNode h = new ListNode(1);
        ListNode head = h;
        h.next = new ListNode(2);
        h = h.next;
        h.next = new ListNode(3);
        h = h.next;
        h.next = new ListNode(4);
        h = h.next;
        h.next = new ListNode(5);

        ListNode listNode = removeNthFromEnd(head, 2);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode h = head;
        for (int i = 0; i < n - 1; i++) {
            if (h == null) {
                break;
            }
            h = h.next;
        }

        if (h == null) {
            return head;
        }

        ListNode delete = head;
        // 待删除的前置节点
        ListNode deletePre = null;
        while (h.next != null) {
            h = h.next;
            deletePre = delete;
            delete = delete.next;
        }

        if (delete == head) {
            ListNode r = head.next;
            head.next = null;
            return r;
        }
        deletePre.next = deletePre.next.next;
        return head;
    }
}
